<?php
namespace app\models;

use fastphp\base\Model;

class User extends Model
{
    protected $table = 'user';
    public static function getGravatar($email, $s = 80, $d = 'mp', $r = 'g', $img = false, $atts = array()) {
        $url = 'https://www.gravatar.com/avatar/';
        $url .= md5(strtolower(trim($email)));
        $url .= "?s=$s&d=$d&r=$r";
        if ($img) {
            $url = '<img src="' . $url . '"';
            foreach ($atts as $key => $val)
                $url .= ' ' . $key . '="' . $val . '"';
                $url .= ' />';
        }
        return $url;
    }
    public function getById($id)
    {
        return (new User())->where(['id=?'], [$id])->fetch();
    }
    public function getByUser($id)
    {
        return (new User())->where(['user=?'], [$id])->fetch();
    }
    public static function login(&$message)
    {
        if (!empty(@$_POST['username']) && isset($_POST['password'])) {
            if (($user = (new User())->getByUser($_POST['username']))) {
                if ($user['password'] == md5(md5(md5($_POST['password'].'233')))) {
                    $_SESSION['username'] = $user['user'];
                    $_SESSION['password'] = $user['password'];
                    $message = '登录成功';
                    return true;
                } else {
                    $message = '密码错误';
                    return false;
                }
            } else {
                $message = '用户名不存在';
                return false;
            }
        } else {
            $message = '非法请求';
            return false;
        }
    }
    public static function isLogin()
    {
        return ($user = (new User())->getByUser(@$_SESSION['username'])) && $user['password'] == @$_SESSION['password'];
    }
    public static function getUser()
    {
        return (new User())->getByUser($_SESSION['username']);
    }
}